package com.boss.fileapp.schedule;

import com.boss.fileapp.consts.FileActionType;
import com.boss.fileapp.entity.FilePathConfig;
import com.boss.fileapp.service.FilePathConfigService;
import com.boss.fileapp.service.ISalaryBackLogService;
import com.boss.fileapp.service.OperateFileService;
import com.boss.fileapp.service.SftpCommonService;
import com.boss.fileapp.util.SftpConnect;
import com.boss.framework.exception.AppRuntimeException;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;


@Component
@EnableScheduling // 通过@EnableScheduling注解开启对计划任务的支持
public class TaskSchedule {
    private static Logger logger = LoggerFactory.getLogger(TaskSchedule.class);

    @Value("${generateFilePath}")
    private String dirPath;

    @Autowired
    private SftpConnect connect;

    @Autowired
    private SftpCommonService sftpCommonService;
    @Autowired
    private OperateFileService operateFileService;
    @Autowired
    private FilePathConfigService filePathConfigService;
    @Autowired
    private ISalaryBackLogService salaryBackLogService;

    @Scheduled(cron = "0 0/10 * * * ?")
    public void createCallRecordsFile() {
        logger.info("----------开始解析回盘文件----------");
        List<String> successFilePathList = new ArrayList<>();
        ChannelSftp sftp = null;
        String returnPath = "";
        try {
            sftp = connect.priKeyConnect();
//            sftp = connect.connect(5);
//            获取远端回盘文件目录路径
            List<FilePathConfig> configList = filePathConfigService.getFilePathConfigByProvince(null);
            if(!CollectionUtils.isEmpty(configList)){
                for (FilePathConfig config : configList) {//扫面每个目录下文件列表
                    returnPath = config.getDownloadDirPath();
                    String province = config.getMofDivCode();
                    String bankName=config.getBankName();
                    List<String> fileNameList = sftpCommonService.getFileNames(sftp, returnPath);
                    if (!CollectionUtils.isEmpty(fileNameList)) {
                        //秘钥文件名
                        String RESYFileName = null;
                        //汇总文件名
                        String REHZFileName = null;
                        for (String fileName : fileNameList) {
                            if (fileName.startsWith(FileActionType.RE_SY_PREFIX)) {
                                RESYFileName = fileName;
                            }
                            if (fileName.startsWith(FileActionType.RE_HZ_PREFIX)) {
                                REHZFileName = fileName;
                            }
                            if("error.txt".equals(fileName)){
                               //添加回盘错误待办事项
                                salaryBackLogService.saveSalaryBackLog(bankName,config.getBankCode(),"bankerror",province);
                                //operateFileService.generateOfferFile(province);
                                //operateFileService.uploadOfferFile(sftp, province,null);
                                sftpCommonService.deleteFile(sftp,returnPath + fileName);
                            }
                        }
                        if(!StringUtils.isEmpty(RESYFileName) && !StringUtils.isEmpty(REHZFileName)){
                            logger.info("----------开始解析{}下的秘钥文件----------",returnPath);
                            String[] SYValue = operateFileService.analysisSYFile(sftp, returnPath, RESYFileName);
                            logger.info("----------解析{}下的秘钥文件完毕----------",returnPath);
                            String sKey = SYValue[0];
                            String MACValue = SYValue[1];
                            logger.info("----------开始解析{}下的回盘文件----------",returnPath);
                            //解析回盘汇总文件
                            int flag=operateFileService.analysisOfferFile(sftp, returnPath, REHZFileName, sKey, MACValue, province);

                            if(flag>0) {//添加银行回盘待办事项
                                salaryBackLogService.saveSalaryBackLog(bankName, config.getBankCode(), "bankback", province);
                            }else{
                                salaryBackLogService.saveSalaryBackLog(bankName, config.getBankCode(), "bankbacknof", province);
                            }
                            logger.info("----------解析{}下的回盘文件完毕----------",returnPath);
                            successFilePathList.add(returnPath + RESYFileName);
                            successFilePathList.add(returnPath + REHZFileName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("回盘文件解析异常：",e);
//            创建并上传error.txt文件
            Path path = Paths.get(dirPath+"error.txt");
            InputStream inputStream = null;
            try {
                Files.createFile(path);
                inputStream = Files.newInputStream(path);
                if(sftp != null){
                    String uploadPath = filePathConfigService.getUploadDirByDownloadDir(returnPath);
                    sftp.cd(uploadPath);
                    sftp.put(inputStream, "error.txt" , 1);
                    Files.deleteIfExists(path);
                }else{
                    throw new AppRuntimeException("sftp连接中断！");
                }
            } catch (IOException | SftpException e1) {
                logger.warn("定时处理回盘文件：创建error.txt文件发生异常！",e);
            } finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        } finally {
            if(sftp != null && !CollectionUtils.isEmpty(successFilePathList)){
                for(String filePath : successFilePathList){
                    try {
                        sftpCommonService.deleteFile(sftp, filePath);
                    } catch (Exception e) {
                        logger.warn("定时处理回盘文件：删除远端文件失败！",e);
                    }
                }
            }
            connect.disconnect(sftp);
            logger.info("----------解析回盘文件结束----------");
        }
    }

}